#!/usr/bin/python
# -*- coding: UTF-8 -*-
import datetime
import os
import threading
import time
from tkinter import messagebox

from selenium import webdriver

from auto import Properties, Constant


def open_chrome():
    url = Properties.get_g_url()
    chrome_driver = "C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"
    os.environ["webdriver.chrome.driver"] = chrome_driver
    driver = webdriver.Chrome(chrome_driver)  # 模拟打开浏览器
    driver.get(url)
    time.sleep(1)
    driver.find_element_by_id("user_login").send_keys(Properties.get_g_name())
    driver.find_element_by_id("user_password").send_keys(Properties.get_g_pass())
    driver.find_element_by_name("commit").click()
    return driver


def get_now_time():
    return datetime.datetime.now().strftime('%Y%m%d_%H%M')


def trade_web(tag):
    url = Properties.get_g_url()
    driver = open_chrome()
    driver.get(url + "mycp_bakend/trade-web")
    commit_msg = driver.find_element_by_class_name("commit-row-message").text

    driver.get(url + "mycp_bakend/trade-web/tags/new")
    driver.find_element_by_id("tag_name").send_keys(tag + get_now_time())
    driver.find_element_by_id("release_description").send_keys(commit_msg)


def service_provider(tag):
    url = Properties.get_g_url()
    driver = open_chrome()
    driver.get(url + "mycp_bakend/service-provider")
    commit_msg = driver.find_element_by_class_name("commit-row-message").text

    driver.get(url + "mycp_bakend/service-provider/tags/new")
    driver.find_element_by_id("tag_name").send_keys(tag + get_now_time())
    driver.find_element_by_id("release_description").send_keys(commit_msg)


def start_tag(tag, project):
    if project == Constant.TRADE:
        threading.Thread(target=trade_web, args=(tag,)).start()
    elif project == Constant.PROVIDER:
        threading.Thread(target=service_provider, args=(tag,)).start()
    else:
        messagebox.showwarning(title='温馨提示', message='【' + project + '】项目暂不支持此操作！')
